package com.epusn.rewa.controller;


import java.util.Base64;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import com.epusn.rewa.util.AESUtil;
import com.epusn.rewa.util.EncryptoUtils;
import com.epusn.rewa.util.RSAUtils;


@RestController
@RequestMapping("/test")
public class EncryptoController extends BaseController{
 
    @RequestMapping(method = RequestMethod.GET, value = "")
    public ModelAndView successPay(ModelAndView mav) throws Exception{
    	String json = "123abc";
		//生成一个对称密钥
		byte[] initKey = AESUtil.initKey();
		//对json敏感数据进行对称加密
		byte[] encryptAES = AESUtil.encryptAES(json.getBytes(), initKey);
		//进行base64加密
		String encode = Base64.getUrlEncoder().encodeToString(encryptAES);
		

		//获取公钥
		String publicKey = EncryptoUtils.getPublicKey();
		//对对称密钥进行非对称加密
		byte[] encryptInitKeyByPublicKeyByte = RSAUtils.encryptByPublicKey(initKey, publicKey.getBytes());
		//进行base64加密
		String encodeInitKey = Base64.getUrlEncoder().encodeToString(encryptInitKeyByPublicKeyByte);
		
		
		//对公钥进行base64编码
		String encodePublicKey = Base64.getUrlEncoder().encodeToString(publicKey.getBytes());
    	
		/**
		 * 注意：
		 * 1.一定要先加密再使用base64进行编码，因为直接加密出来的字符串有换行，特殊字符等，是不能写在url上面的，且base64必须使用getUrlEncoder()方法，不能使用getEncoder，
		 * 原因还是这是url，有诸多限制
		 */
		String redirectUrl = "redirect:http://localhost:8080/test/tosuccess?payment=" + encode+"&balance="+encodeInitKey+"&publickey="+encodePublicKey;
    	mav.setViewName(redirectUrl);
        return mav;
    }
    
    @RequestMapping(value="/tosuccess")
	    public String toSuccess(String payment,String balance,String publickey) throws Exception{
    	//对三个参数进行base64解码
		byte[] publicKeyByte = Base64.getUrlDecoder().decode(publickey);
		byte[] balanceByte = Base64.getUrlDecoder().decode(balance);
		byte[] decode = Base64.getUrlDecoder().decode(payment);
		
		//先根据公钥获取私钥
		String privateKey = EncryptoUtils.getPrivateKey(new String(publicKeyByte));
		//对密钥进行非对称解密
		byte[] decryptByPrivateKey = RSAUtils.decryptByPrivateKey(balanceByte, privateKey.getBytes());
		//对称解密内容
		byte[] decryptAES = AESUtil.decryptAES(decode, decryptByPrivateKey);
	    return new String(decryptAES);
    }
}
